package com.changgou.web.gateway.fiter;

import com.changgou.web.gateway.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private AuthService authService;

    private String LOGIN_PAGE="http://localhost:8001/api/oauth/toLogin?from=";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断请求路径是否需要令牌
        String path = request.getURI().getPath();
        if(UrlFilter.hasAuthorize(path)){
            return chain.filter(exchange);
        }
        //需要令牌的话,判断cookie中是否有jti
        String jti=authService.getJtiFromCookie(request);
        if(StringUtils.isEmpty(jti)){
//            //拒绝访问
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            return response.setComplete();
            return this.toLoginPage(response,path);
        }
        //从redis中获取jwt
        String jwt=authService.getJwtFromRedis(jti);
        if(StringUtils.isEmpty(jwt)){
//            //拒绝访问
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            return response.setComplete();
            return this.toLoginPage(response,path);
        }
        //对当前请求进行增强
        request.mutate().header("Authorization","Bearer "+jwt);
        return chain.filter(exchange);
    }

    private Mono<Void> toLoginPage(ServerHttpResponse response,String fromPath) {
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("location",LOGIN_PAGE+fromPath);
        return response.setComplete();
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
